<?php 

function pay_huode_codes($weer_num=1,$shopinfo=null,&$ret_data=null){
 
		$db = System::DOWN_sys_class("model");
		$ret_data['query'] = true;
		$table = '@#_'.$shopinfo['codes_table'];
		$codes_arr = array();
		$codes_one = $db->YOne("select id,s_id,s_cid,s_len,s_codes,s_codes_tmp from `$table` where `s_id` = '$shopinfo[id]' order by `s_cid` DESC  LIMIT 1 for update");
		$codes_arr[$codes_one['s_cid']] = $codes_one;		
		$codes_count_len = $codes_arr[$codes_one['s_cid']]['s_len'];

		if($codes_count_len < $weer_num && $codes_one['s_cid'] > 1){		
			for($i=$codes_one['s_cid']-1;$i>=1;$i--):
				$codes_arr[$i] = $db->YOne("select id,s_id,s_cid,s_len,s_codes from `$table` where `s_id` = '$shopinfo[id]' and `s_cid` = '$i'  LIMIT 1 for update");
				$codes_count_len += $codes_arr[$i]['s_len'];
				if($codes_count_len > $weer_num)  break;
			endfor;
		}
		
		if($codes_count_len < $weer_num) $weer_num = $codes_count_len;
		
		$ret_data['user_code'] = '';
		$ret_data['user_code_len'] = 0;
		
		foreach($codes_arr as $icodes){			
			$u_num = $weer_num;			
			$icodes['s_codes'] = unserialize($icodes['s_codes']);	
			$code_tmp_arr = array_slice($icodes['s_codes'],0,$u_num);
			$ret_data['user_code'] .= implode(',',$code_tmp_arr);	
			$code_tmp_arr_len = count($code_tmp_arr);
			
			if($code_tmp_arr_len < $u_num){
				$ret_data['user_code'] .= ',';
			}
			
			$icodes['s_codes'] = array_slice($icodes['s_codes'],$u_num,count($icodes['s_codes']));
			$icode_sub = count($icodes['s_codes']);		
			$icodes['s_codes'] = serialize($icodes['s_codes']);

			//修复机器人 
			$jiqiren=$db->YOne("select * from `@#_shangpin` where `id`='$icodes[s_id]' for update");
			$icodessss['s_codes_tmp'] = unserialize($icodes['s_codes_tmp']);	
			$srci=$jiqiren['zongrenshu']-$jiqiren['canyurenshu']-$u_num;
			$srci2=fmod(($jiqiren['zongrenshu']-$srci),3000);
			$icodesnew = array_slice($icodessss['s_codes_tmp'],$srci2,count($icodessss['s_codes_tmp']));
			$icodesnewss=serialize($icodesnew);
			$counts1=$db->Ylist("select id,s_id,s_cid,s_len,s_codes  from `$table` where `s_id` = '$shopinfo[id]'");
			foreach ($counts1 as $value)
			{
				$kkkkk +=$value[s_len];
			}


		

			if(!$icode_sub){
				$query = $db->Query("UPDATE `$table` SET `s_cid` = '0',`s_codes` = '$icodesnewss',`s_len` = '$icode_sub' where `id` = '$icodes[id]'");
				if(!$query)$ret_data['query'] = false;
			}else{		
				$query = $db->Query("UPDATE `$table` SET `s_codes` = '$icodes[s_codes]',`s_len` = '$icode_sub' where `id` = '$icodes[id]'");

				if(!$query)$ret_data['query'] = false;
			}
			$ret_data['user_code_len'] += $code_tmp_arr_len;
			$weer_num  = $weer_num - $code_tmp_arr_len;
			
			//修复机器人结束
			
			
		}
		
}


//生成订单号
function pay_huode_dingdan($dingdanzhui=''){
	return $dingdanzhui.time().substr(microtime(),2,6).rand(0,9);
}


/*
	揭晓与插入商品
	@shop   商品数据
*/

function pay_insert_shoplist($shop='',$type=''){
	
	$g_c_x = System::DOWN_App_config("get_code_x",'',"pay");
	if(is_array($g_c_x) && isset($g_c_x['class'])){
		$gcx_db = System::DOWN_App_class($g_c_x['class'],"pay");
	}else{
		$g_c_x = array("class"=>"tocode");
		$gcx_db = System::DOWN_App_class($g_c_x['class'],"pay");
	}
		
	$gcx_db->config($shop,$type);
	$gcx_db->get_run_code();
	$ret_data = $gcx_db->returns();
	
	
	
}

/*
	揭晓与插入商品
	@shop   商品数据
*/
function pay_insert_shop($shop='',$type=''){
	echo "entered pay.fun.php ";
	//$myfile = fopen("ctest.txt", "a");
	//fwrite($myfile, "当前时间".microtime(true)." 进入pay_insert_shop\n");
	$time=sprintf("%.3f",microtime(true)+(int)System::DOWN_sys_config('system','goods_end_time'));
	$db = System::DOWN_sys_class("model");
	if($shop['xsjx_time'] != '0'){
		return $db->Query("UPDATE `@#_shangpin` SET `canyurenshu`=`zongrenshu`,	`shenyurenshu` = '0' where `id` = '$shop[id]'");
	}
	//fwrite($myfile, "当前时间".microtime(true)." 初始化完毕\n");

	$tocode = System::DOWN_App_class("tocode","pay");
	//fwrite($myfile, "当前时间".microtime(true)." 引入完tocode\n");
	$tocode->shop = $shop;	
	//fwrite($myfile, "当前时间".microtime(true)." 开始执行yunxing_shop\n");
	$tocode->yunxing_shop($time,100,$shop['canyurenshu'],$shop);

	//fwrite($myfile, "当前时间".microtime(true)." 执行完yunxing_shop\n");
	$code = $tocode->go_code;
	$content = addslashes($tocode->go_content);
	$counttime = $tocode->count_time;
	echo "(开奖依据)code:$code, content:$content, counttime:$counttime ";
	//201511117新增，判断是否指定中奖//
	/*if($shop['quyu_begin'] && $shop['quyu_end']){
		$ex_info=$db->YOne("select * from `@#_yonghu_yys_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `uid` >='{$shop['quyu_begin']}' and `uid` <='{$shop['quyu_end']}' order by rand() limit 1");
	    if($ex_info['goucode']){
	    	$ex_code=explode(",",$ex_info['goucode']);
			$ex_count=count($ex_code);
			$ex_rand=rand(0,$ex_count-1);
			if(!empty($ex_code[$ex_rand])){
				$chazhi=$ex_code[$ex_rand]-$code;
				if($chazhi>0)$counttime=$counttime+$chazhi;
				else $counttime=$counttime-abs($chazhi);
				$code=$ex_code[$ex_rand];

				if(!empty($chazhi)){
					$last_info=$db->YOne("select * from `@#_yonghu_yys_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' order by id desc limit 1");
					$time_t_str = str_replace('.','',$last_info['time']);
					$time_str = bcadd($time_t_str,$chazhi);
					$time_arr = str_split($time_str,10);
					$str_t_time = $time_arr[0].'.'.$time_arr[1];
					$db->Query("UPDATE `@#_yonghu_yys_record` SET `time`='$str_t_time' where `id` = '{$last_info['id']}'");
					$tocode = System::DOWN_App_class("tocode","pay");
					$tocode->shop = $shop;
					$tocode->yunxing_shop($time,100,$shop['canyurenshu'],$shop);
					$content = addslashes($tocode->go_content);
				}
			}
	    }
	}*/
	/////////////////
	
	//fwrite($myfile, "当前时间".microtime(true)." 即将查询u_go_info & u_info\n");
	$u_go_info = $db->YOne("select * from `@#_yonghu_yys_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `goucode` LIKE  '%$code%'");	
	$u_info = $db->YOne("select uid,username,email,mobile,img from `@#_yonghu` where `uid` = '$u_go_info[uid]'");

	echo "inside pay.fun.php shop:";
	print_r($shop);
	echo "inside pay.fun.php u_go_info:";
	print_r($u_go_info);
	//fwrite($myfile, "当前时间".microtime(true)." 即将更新商品 counttime： $counttime\n");
	//更新商品
	echo "inside pay.fun.php u_info:";
	print_r($u_info);
	$query = true;
	if($u_info){
		$u_info['username'] = _htmtguolv($u_info['username']);
		$q_yonghu = serialize($u_info);
		$gtimes = (int)System::DOWN_sys_config('system','goods_end_time');
		if($gtimes == 0 || $gtimes == 1){
			$q_showtime = 'N';
		}else{
			$q_showtime = 'Y';
		}

		$cqssc = $db->YOne("select * from `@#_lottery_code` where `id` = '".$tocode->go_sscid."'");
		$cqsscnum = str_replace(",","",$cqssc['opencode']);
		
		$sqlss = "UPDATE `@#_shangpin` SET 
					`canyurenshu`=`zongrenshu`,
					`shenyurenshu` = '0',
					`q_uid` = '$u_info[uid]',
					`q_user` = '$q_yonghu',
					`q_user_code` = '$code',
					`q_content`	= '$content',
					`q_counttime` ='$counttime',
					`q_end_time` = '$time',
					`q_showtime` = '$q_showtime',
					`cqsscnum` = '$cqsscnum',
					`cqssc` = '$cqssc[id]',
					`cqssqs` = '$cqssc[expect]'
					where `id` = '$shop[id]'";
							 
		echo "inside pay.fun.php sqlss:";
		print_r($sqlss);
			$hhj = "UPDATE `yys_card` SET
					`uid` = '$u_info[uid]',
					`shopid` = '$shop[id]' 
					where `status` = '0'
					and `money` = '$shop[money]' 
					ORDER BY `id` DESC 
					limit 1";				 

	
		$q = $db->Query($sqlss);
		$db->Query($hhj);
		if(!$q)$query = false;	
				
		if($q){
			
			//处理商户共赢
			$winwinCommission = $db->YOne("select * from `yys_configs` where `name`='winwinCommission'");
			$supplier = $db->YOne("select * from `@#_supplier` where `id` = '$shop[supplierId]'");
			$supplier_user = $db->YOne("select * from `@#_yonghu` where `uid` = '$supplier[uid]'");
			$money = $shop['yuanjia'] * $winwinCommission['value'];
			$yonghu_zhanghao = array(
				'uid' => $supplier_user['uid'],
				'type' => '1',
				'pay' => '系统',
				'pay_type' => 2,
				'qishu' => $shop['qishu'],
				'yuanjia' => $shop['yuanjia'],
				'content' => '共赢收益【'.$shop['title'].'】'.$money.'元',
				'money' => $money,
				'time' => time(),
				'sid' => $shop['supplierId'],
			);
			insertInto($yonghu_zhanghao,'yonghu_zhanghao');
			updateSet(array('money'=>$supplier_user['money']+$money),'yonghu',$supplier_user['uid'],'uid');

			
			//邀请收益
			if(!$supplier['pid']){
				$pid = $db->YOne("select * from `yys_configs` where `name`='defaultSupplierInviteId'");
			}else{
				$pid = $supplier['pid'];
			}
			if($pid){
				$interactiveCommission = $db->YOne("select * from `yys_configs` where `name`='interactiveCommission'");
				$pid_supplier = $db->YOne("select * from `@#_supplier` where `id` = '$pid'");
				$pid_supplier_user = $db->YOne("select * from `@#_yonghu` where `uid` = '$pid_supplier[uid]'");
				$pid_money = $shop['yuanjia'] * $interactiveCommission['value'];
				$pid_yonghu_zhanghao = array(
					'uid' => $pid_supplier_user['uid'],
					'type' => '1',
					'pay' => '系统',
					'pay_type' => 3,
					'qishu' => $shop['qishu'],
					'yuanjia' => $shop['yuanjia'],
					'content' => '邀请收益【'.$shop['title'].'】'.$pid_money.'元',
					'money' => $pid_money,
					'time' => time(),
					'sid' => $shop['supplierId'],
				);
				insertInto($pid_yonghu_zhanghao,'yonghu_zhanghao');
				updateSet(array('money'=>$pid_supplier_user['money']+$money),'yonghu',$pid_supplier_user['uid'],'uid');
						
				//				file_put_contents('u_go_info.txt',var_export($pid_yonghu_zhanghao,true)."\r\n",FILE_APPEND);
			}

			
			
			//push_weixin_msg_autolottery($shop['id'],$shop['title'],$shop['qishu'],$code,$u_go_info[uid]);
			
			//以优惠券的形式转给客户
			$yonghu_coupon = array();
			$yonghu_coupon['uid'] = $u_info['uid'];
			$yonghu_coupon['code'] = date('YmdHis').rand(10000,99999);
			$yonghu_coupon['password'] = substr(uniqid(),0,8);
			$yonghu_coupon['money'] = $shop['yuanjia'];
			$yonghu_coupon['sid'] = $shop['supplierId'];
			$yonghu_coupon['create_time'] = time();
			$yonghu_coupon['sid'] = $shop['supplierId'];
			$yonghu_coupon['type'] = '0';
			$yonghu_coupon['shopid'] = $shop['id'];
			insertInto($yonghu_coupon,'yonghu_coupon');
			//			file_put_contents('u_go_info.txt',var_export($yonghu_coupon,true)."\r\n",FILE_APPEND);


			//推送给供应商
			/*if($shop['uid']){
				$openid = $db->YOne("select `openid` from `@#_yonghu` where `uid` = '$shop[uid]'");
				if($openid['openid']){
					$username = $db->YOne("select `username` from `@#_yonghu` where `uid` = '$shop[uid]'");
					$pushData = array(
						'username' => $username['username'],
						'shopname' => $shop['title'],
					);

					push_wx_msg_new('gysyxdd',$openid['openid'],$pushData);
				}
			}
			
			
			$wx_record = $db->YList("select * from `@#_yonghu_yys_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' group by `uid`");
			foreach($wx_record as $wkey => $wone){
				$openid = $db->YOne("select `openid` from `@#_yonghu` where `uid` = '$wone[uid]'");
				if($openid['openid']){
					$username = $db->YOne("select `username` from `@#_yonghu` where `uid` = '$wone[uid]'");
					$pushData = array(
						'username' => $username['username'],
						'qishu' => $shop['qishu'],
						'shopname' => $shop['title'],
						'webname'	=> _yys("web_name"),
					);

					push_wx_msg_new('kjts',$openid['openid'],$pushData);
				}
			}*/
			
				
			$q = $db->Query("UPDATE `@#_yonghu_yys_record` SET `huode` = '$code' where `id` = '$u_go_info[id]' and `code` = '$u_go_info[code]' and `uid` = '$u_go_info[uid]' and `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]'");
			if(!$q) {
				$query = false;
			}else{
				$post_arr= array("uid"=>$u_info['uid'],"gid"=>$shop['id'],"send"=>1);
				_g_YYSabcde(LOCAL_PATH.'/api/send/send_shop_code',false,$post_arr);
			}
		}else{
			$query =  false;
		}
	}else{	
		$query =  false;
	}
	
	/*新建*/
	if($query){
		//sleep(3);
		if($shop['qishu'] < $shop['maxqishu']){		
			$maxinfo = $db->YOne("select * from `@#_shangpin` where `sid` = '$shop[sid]' order by `qishu` DESC LIMIT 1");
			if(!$maxinfo){
				$maxinfo=array("qishu"=>$shop['qishu']);
			}			
			System::DOWN_App_fun("content",G_ADMIN_DIR);
			//fwrite($myfile, "当前时间".microtime(true)." 即将进入content_add_shop_install\n");
			$intall = content_add_shop_install($maxinfo,false);		
			//fwrite($myfile, "当前时间".microtime(true)." 完毕content_add_shop_installl\n");
			if(!$intall)
			{
				//fclose(($myfile);
				return $query;
			}
		}
	}
	//fclose(($myfile);
	return $query;
}


/*
	欢惠券基金
	go_number @欢惠券人次
*/
function pay_go_jijin($go_number=null){
	if(!$go_number)return true;
	$db = System::DOWN_sys_class("model");
	$fund = $db->YOne("select * from `@#_jijin` where 1");
	if($fund && $fund['fund_off']){
		$money = $fund['fund_money'] * $go_number + $fund['fund_count_money'];
		return $db->Query("UPDATE `@#_jijin` SET `fund_count_money` = '$money'");
	}else{
		return true;
	}
}


/*
	用户佣金
	uid 		用户id
	dingdancode	@订单号
*/
function pay_go_yongjin($uid=null,$dingdancode=null,$uid2=null,$uid3=null,$type=null){
	if(!$uid || !$dingdancode)return true;
	$cashoutid = $uid;
	$db = System::DOWN_sys_class("model");$time=time();
	$config = System::DOWN_App_config("user_fufen",'','member');//福分/经验/佣金
	$yesyaoqing=$db->YOne("SELECT * FROM `@#_yonghu` WHERE `uid`='$uid'");
	if($yesyaoqing['isfee']==0)
	$db -> Query("update `@#_yonghu` set isfee = 1 where `uid` ='$uid'");

	if($yesyaoqing['yaoqing']){
		$yjarr = get_pay_yjarr($uid);
		$yongjin1=$yjarr['ceng1'];
		$yongjin2=$yjarr['ceng2']; 
		$yongjin3=$yjarr['ceng3']; 
		//$yongjin4=$yjarr['ceng4']; 
		//$yongjin5=$yjarr['ceng5']; 
	}else{
		return true;
	}	

	/* 	$yongjin = floatval(substr(sprintf("%.3f",$yongjin), 0, -1));
	$yongjin2 = floatval(substr(sprintf("%.3f",$yongjin2), 0, -1));
	$yongjin3 = floatval(substr(sprintf("%.3f",$yongjin3), 0, -1)); */
	if($type == 'zg'){
		$table = '@#_zg_yonghu_yys_record';
	}else{
		$table = '@#_yonghu_yys_record';
	}
	$gorecode=$db->Ylist("SELECT * FROM `$table` WHERE `code`='$dingdancode'");
	file_put_contents('pay_go_jijin.txt',var_export($gorecode,true)."\r\n",FILE_APPEND);

	foreach($gorecode as $val){
		$y_money1=$val['moneycount'] * $yongjin1;
		$y_money2=$val['moneycount'] * $yongjin2;
		$y_money3=$val['moneycount'] * $yongjin3;
		//$y_money4=$val['moneycount'] * $yongjin4;
		//$y_money5=$val['moneycount'] * $yongjin5;

		$content="(第".$val['shopqishu']."期)".$val['shopname'];

		if(isset($yjarr['uid1']) && $yjarr['uid1']>0)
		{
			$uid1 = $yjarr['uid1'];
			$db->Query("INSERT INTO `@#_yonghu_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`time`,`cashoutid`)VALUES('$uid1','1','$content','$val[shopid]','$y_money1','$val[moneycount]','$time','$cashoutid' )");
			$db -> Query("update `@#_yonghu` set yongjin = yongjin+'$y_money1' where `uid` ='$uid1'");
		}
		if(isset($yjarr['uid2']) && $yjarr['uid2']>0)
		{
			$uid2 = $yjarr['uid2'];
			$db->Query("INSERT INTO `@#_yonghu_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`time`,`cashoutid`)VALUES('$uid2','1','$content','$val[shopid]','$y_money2','$val[moneycount]','$time','$cashoutid' )");
			$db -> Query("update `@#_yonghu` set yongjin = yongjin+'$y_money2' where `uid` ='$uid2'");
		}
		if(isset($yjarr['uid3']) && $yjarr['uid3']>0)
		{
			$uid3 = $yjarr['uid3'];
			$db->Query("INSERT INTO `@#_yonghu_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`time`,`cashoutid`)VALUES('$uid3','1','$content','$val[shopid]','$y_money3','$val[moneycount]','$time','$cashoutid' )");
			$db -> Query("update `@#_yonghu` set yongjin = yongjin+'$y_money3' where `uid` ='$uid3'");
		}
		/*if(isset($yjarr['uid4']) && $yjarr['uid4']>0)
		{
			$uid4 = $yjarr['uid4'];
			$db->Query("INSERT INTO `@#_yonghu_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`time`,`cashoutid`)VALUES('$uid4','1','$content','$val[shopid]','$y_money4','$val[moneycount]','$time','$cashoutid' )");
			$db -> Query("update `@#_yonghu` set yongjin = yongjin+'$y_money4' where `uid` ='$uid4'");
		}
		if(isset($yjarr['uid5']) && $yjarr['uid5']>0)
		{
			$uid5 = $yjarr['uid5'];
			$db->Query("INSERT INTO `@#_yonghu_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`time`,`cashoutid`)VALUES('$uid5','1','$content','$val[shopid]','$y_money5','$val[moneycount]','$time','$cashoutid' )");
			$db -> Query("update `@#_yonghu` set yongjin = yongjin+'$y_money5' where `uid` ='$uid5'");
		}*/
	}
	
}

//得到5级分销数组包括用户id和佣金比例    by 274276153 20160119
function get_pay_yjarr($uid){
	$yjarr = null;
	$num = 1;
	$db=System::DOWN_sys_class('model');
	$config = System::DOWN_App_config("user_fufen");
	
	while($uid>0 && $num<=5){
		$yaoqing = $db->YOne("SELECT `yaoqing`,`uid` FROM `@#_yonghu` WHERE `uid`='$uid'");
		$uid = $yaoqing['yaoqing'];
		if($uid>0){
			$yjarr["uid{$num}"]=$uid;
			
			$invifriends=$db->Ylist("select * from `@#_yonghu` where `yaoqing`='$uid' ORDER BY `time` DESC");	
			$involvedtotal=count($invifriends);			
			if($involvedtotal <= $config['renshuji1']){
				$yjarr["ceng{$num}"] = $config["yongjinc{$num}j1"];
			}else if($involvedtotal > $config['renshuji1'] && $involvedtotal <= $config['renshuji2']){
				$yjarr["ceng{$num}"] = $config["yongjinc{$num}j2"];
			}else if($involvedtotal > $config['renshuji2'] && $involvedtotal <= $config['renshuji3']){
				$yjarr["ceng{$num}"] = $config["yongjinc{$num}j3"];
			}else{
				$yjarr["ceng{$num}"] = $config["yongjinc{$num}j4"];
			}
		}
		$num++;
	}
	return $yjarr;
}


/*
*	星级老板
*/

function startPayMargin($uid,$orderCode){
	
	$db = System::DOWN_sys_class('model');
	
	//第一步：查询这个用户是否存在上级
	$userInfo = $db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
	
	if($userInfo['yaoqing']){
		
		//第二步：取出上级，以及上级的等级，为0级则不进行任何返还
		$inviteId = $userInfo['yaoqing'];
		$inviteUser = $db->YOne("select * from `@#_yonghu` where `uid` = '$userInfo[yaoqing]'");
		$grade = $inviteUser['grade'];
		
		if($inviteUser && $grade > 0){
			//第三步：查询有没有这个单
			$order = $db->YList("select * from `@#_yonghu_yys_record` where `code` = '$orderCode'");
			
			//第四步：存在订单，查看价格并开始逐个返还
			if($order){
				foreach($order as $key => $one){
					//第五步：取出对应的商品返还金额
					$shangpin = $db->YOne("select * from `@#_shangpin` where `id` = '$one[shopid]'");
					
					//通过下线等级取得返还金额
					$nextGrade = $userInfo['grade'];

					//如果上线是3星，则获取最高返还
					if($grade == 3){
						if($nextGrade == 3){
							$money = $shangpin['thirdYongjin'];
						}elseif($nextGrade == 2){
							$money = $shangpin['secondYongjin'];
						}elseif($nextGrade == 1){
							$money = $shangpin['firstYongjin'];
						}

						//基础参数
						$content = "合伙人购买商品：".$shangpin['title'];
						$ygmoney = $one['moneycount'];
						$shopid	 = $one['shopid'];
					}elseif($grade == 2){
					
						//如果是2星，只获得2星和1星
						if($nextGrade == 2){
							$money = $shangpin['secondYongjin'];
						}elseif($nextGrade == 1){
							$money = $shangpin['firstYongjin'];
						}				
						
						//基础参数
						$content = "合伙人购买商品：".$shangpin['title'];
						$ygmoney = $one['moneycount'];
						$shopid	 = $one['shopid'];
					}elseif($grade == 1){
						
						//如果是1星，只获取1星
						if($grade == 1){
							$money = $shangpin['firstYongjin'];
						}
						
						//基础参数
						$content = "合伙人购买商品：".$shangpin['title'];
						$ygmoney = $one['moneycount'];
						$shopid	 = $one['shopid'];
					}
					
					
					//金额非0，则进行返还
					if($money > 0){
											
						//进行返还，先入库到会员账户明细
						$time = time();
						$noteSql  = "INSERT INTO `@#_fanyong_recodes` (`uid`,`type`,`content`,`shopid`,`money`,`time`,`ygmoney`,`inviteId`,`inviteMargin`) VALUES ";
						$noteSql .= "('$inviteId','1','$content','$shopid','$money','$time','$ygmoney','$uid','$grade')";
						$res = $db->Query($noteSql);
						if($res){
							//写入LIST
							$fanyongSql = "INSERT INTO `@#_fanyong_list` (`uid`,`fanyong_id`,`price`,`fanyong_time`,`type`) VALUES ('$inviteId','$uid','$money','$time','1')";
							$res = $db->Query($fanyongSql);
							//更新对应会员的佣金
							if($res){
								$updateSql = "UPDATE `@#_yonghu` SET `fmoney` = `fmoney` + '$money' WHERE `uid` = '$inviteId'";
								$db->Query($updateSql);
							}
						}
						
						//写入日志文件，以便于测试
						file_put_contents('noteSql.txt',var_export($noteSql)."\r\n",FILE_APPEND);
						file_put_contents('noteSql.txt',var_export($fanyongSql)."\r\n",FILE_APPEND);
						file_put_contents('noteSql.txt',var_export($updateSql)."\r\n",FILE_APPEND);
					}
				}
			}
		}
	}
}


function zgreturn($dingdancode){
	if($dingdancode){
		$db = System::DOWN_sys_class('model');
		$dingdanlist = $db->YList("select * from `@#_zg_yonghu_yys_record` where `id` = '$dingdancode'");

		$uid = $dingdanlist['0']['uid'];
		$member = $db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
		if($dingdanlist && $member['risk'] != 'high'){
			foreach($dingdanlist as $key => $one){
				//是否参与返还
				$shop = $db->YOne("select * from `@#_zg_shangpin` where `id` = '$one[shopid]'");
				if($shop['cashBack']){
					$uid = $one['uid'];
					$userinfo = $db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
					//$countMoney = 0;
					//foreach($dingdanlist as $key => $one){
					$countMoney = $one['moneycount'];
					//}
					$returnConfig = System::DOWN_App_config("commision","","admin");
					$totalMoney = $countMoney * $returnConfig['commision'] / 100;
					$dayMoney = $totalMoney / $returnConfig['commisionDay'];
					$time = time();
					$baseTime = date('Y-m-d');
					for($i=1;$i<=$returnConfig[commisionDay];$i++){
						$addTime = strtotime($baseTime) + $i * 3600 * 24;
						$noteSql  = "INSERT INTO `@#_zg_return_list` (`uid`,`orderId`,`orderSn`,`shopname`,`money`,`days`,`dayMoney`,`createTime`,`addTime`) VALUES ";
						$noteSql .= "('$uid','$one[id]','$dingdancode','$one[shopname]','$totalMoney','$returnConfig[commisionDay]','$dayMoney','$time','$addTime')";
						$db->Query($noteSql);
					}

					$pushData = array(
						'money' => $totalMoney,
						'days' => $returnConfig['commisionDay'],
					);

					push_wx_msg_new('fxcgtz',$userinfo['openid'],$pushData);
				}
			}
		}
	}
	return true;
}


?>

